//组件式实现 todolist

import React, { Component } from "react";

class DemoA extends Component {
    constructor() {
        super()
        this.state = {
            todo: '',
            list: []
        }
    }
    //拿到输入框数据
    getTodo(e) {
        //拿到输入框对象   e.target.value
        this.setState({
            todo: e.target.value
        })
    }
    //将数据保存到下方数组中
    confirm() {
        if (!this.state.todo.trim()) {
            alert('请输入内容')
            return
        }
        this.setState(state => ({
            list: [...state.list, { id: Date.now(), task: state.todo }]
        }))
        this.setState({
            todo: ''
        })
    }
    //绑定enter键添加数据
    addByEnter(e) {
        if (e.keyCode === 13) {
            this.confirm();
        }
    }
    //删除功能
    delTodo(id) {
        this.setState(state => ({
            //删除item.id
            list: state.list.filter(item => item.id !== id)
        }))
    }
    //    返回可视化模板
    render() {
        let { todo } = this.state;
        let { list } = this.state;
        return (
            <div>
                <div>
                    <input type="text" value={todo} onChange={e => this.getTodo(e)} onKeyUp={e => this.addByEnter(e)} />

                    <button onClick={e => this.confirm(e)} >点击添加</button>
                </div>
                <hr />
                <div>
                    {
                        list.map((item, index, arr) => (
                            <ul key={item.id}>
                                <li>
                                    <span>{item.task} </span>

                                    <button onClick={() => this.delTodo(item.id)}  >删除</button>
                                </li>
                            </ul>
                        ))
                    }
                </div>
            </div>
        )
    }
}

export default DemoA;